<template>
  <div v-html="processedMarkdown"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import container from 'markdown-it-container'
import 'highlight.js/styles/github.css'


const md = new MarkdownIt({
  html: true, // 允许 HTML 标签
  breaks: true,
  highlight: function (str, lang) {
    console.log('highlight', str, lang);
    if (lang && hljs.getLanguage(lang)) {
      try {
        const highlightedCode = hljs.highlight(str, { language: lang }).value;
        return highlightedCode
      } catch (e) {
        console.error(e);
      }
    }

    return escapeHtml(str);
  }
})

md.use(container, 'image-describe', {
  render: function (tokens, idx) {
    if (tokens[idx].nesting === 1) {
      // 开始标签
      return '<image-describe>';
    } else {
      // 结束标签
      return '</image-describe>';
    }
  }
});

const markdown = `
这是一个 JSON 代码块：

\`\`\`json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
\`\`\`

这是一个 JavaScript 代码块：

\`\`\`js
function hello() {
    console.log("Hello World");
}
\`\`\`
`;
const processedMarkdown = ref('');


/**
 * 转义 HTML 特殊字符（防止 XSS）
 */
function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

/**
 * 
 * @param html 将 HTML 字符串中的代码块进行包装
 * @returns 包装后的 HTML 字符串
 */
function wrapCodeBlocks(html) {
  const temp = document.createElement('div');
  temp.innerHTML = html;

  const pres = temp.querySelectorAll('pre');

  pres.forEach(pre => {
    const code = pre.querySelector('code');
    if (!code) return;

    const langMatch = code.className.match(/language-(\w+)/);
    const languageType = langMatch ? langMatch[1] : 'text';

    const wrapper = document.createElement('div');
    wrapper.className = 'markdown-code-block';
    wrapper.innerHTML = `
      <div class="code-header">
        <span class="lang-label">${languageType}</span>
        <span class="copy-icon" title="复制" onclick="handleCopyToClipboard(event)">
          <i class="bi bi-copy"></i>
        </span>
      </div>
      <div class="code-content"></div>
    `;

    const codeContent = pre.outerHTML; // 获取原始的 <pre><code>...</code></pre>
    wrapper.querySelector('.code-content').innerHTML = codeContent;

    pre.parentNode.replaceChild(wrapper, pre);
  });

  return temp.innerHTML;
}

onMounted(() => {
  // processedMarkdown.value = replaceCodeBlocks(markdown);
  var markdownStr = "# hello<button_start>按钮开始<button_end><button>按钮</button>\n\n";

  var html = md.render(markdown);
  processedMarkdown.value = wrapCodeBlocks(html)

  const content = `\n                ['目前本井存在的主要风险：C环空过路层气上窜，持续带压。']_{[78]}\n`;
processedMarkdown.value = md.render(content)
console.log(md.render(content));
});
</script>

<style>
.markdown-code-block {
  border: 1px solid #e4e4e4;
  border-radius: 8px;
  background-color: #fafafa;
  font-family: monospace;
  margin: 1rem 0;
  /* 左右留白保持美观 */
  overflow: hidden;
}

.code-header {
  position: sticky;
  top: 0;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #eeeeee;
  color: #535353;
  padding: 6px 12px;
  margin-bottom: 4px;
  /* 减少与下方代码块的距离 */
}

.code-content {
  padding: 12px;
  max-height: 250px;
  overflow-y: auto;
  margin: auto 0; /* 上下居中 */
  /* 避免默认外边距干扰 */
}


.lang-label {
  font-size: 16px;
  color: #000;
  font-family: '微软雅黑', 'Arial', sans-serif;
}

.copy-icon {
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: color 0.2s ease;
}

.copy-icon:hover .bi {
  color: #007bff;
}
</style>